<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList"> </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 明细信息 -->
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />

    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="receiptOrder">
import SetPreference from "@/components/SetPreference/defaultSetPreference"
import {
  downloadFileReceiptOrder,
  // getReceiptOrderPage,
  deleteReceiptOrder,
  submitReceiptOrder,
  revokeReceiptOrder,
  rejectReceiptOrder,
  ratifyReceiptOrder,
  cancelReceiptOrder,
  excelReceiptOrder,
  printReceiptOrder,
  getReceiptOrderCustomizeListPage,
} from '@/api/receipt'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import Modify from './modify'
import detail from './details'
import { fatchTemplateByCode } from '@/api/base'
import { getSupplierAll } from '@/api/core'
const { proxy } = getCurrentInstance()
const detailList = defineAsyncComponent(() => import('./detailList'))

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      supplierAuth: {
        asTbName: 'receipt_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    queryParams: {},
  },
  searchList: [],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('receiptOrder:add'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('receiptOrder:export'),
    },
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('receiptOrder:print'),
    },
    {
      type: 'button',
      label: '下载附件',
      event: downloadFile,
      show: proxy.$permission('receiptOrder:downloadFile'),
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: _search },
    { type: 'button', label: '高级查询', event: _advancedSearchShow },
    { type: 'button', label: '重置', event: _clearSearch },
  ],
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: null,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'receiptAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('receiptOrder:update'),
        ifRender: function (row) {
          return row.status === 1 && row.orderSource === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('receiptOrder:submit'),
        ifRender: function (row) {
          return row.status === 1 && row.orderSource === 1
        },
      },
      {
        label: '审核',
        event: ratify,
        show: proxy.$permission('receiptOrder:ratify'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('receiptOrder:remove'),
        ifRender: function (row) {
          return row.status === 1 && row.orderSource === 1
        },
      },
      {
        label: '驳回',
        event: reject,
        popconfirmText: '驳回后将改变数据,是否继续？',
        show: proxy.$permission('receiptOrder:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '撤回',
        event: revoke,
        popconfirmText: '撤回后将改变数据,是否继续？',
        show: proxy.$permission('receiptOrder:revoke'),
        ifRender: function (row) {
          return row.status === 2 && row.orderSource === 1
        },
      },

      {
        label: '作废',
        event: cancel,
        popconfirmText: '作废后将改变数据,是否继续？',
        show: proxy.$permission('receiptOrder:invalid'),
        ifRender: function (row) {
          return row.status === 5
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const detailListInfo = reactive({
  visible: false,
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'receiptOrder' && el.url === val.url) {
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.value.visible = true
                  let data = {
                    id: val.businessId,
                  }
                  detailInfo.value.tableRow = data
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    { deep: true, immediate: true }
  )
})
onDeactivated(() => {
  stopWatch()
})

const canConfirm = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 2).length === 0
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 2).length === 0
  )
})
const canDelete = computed(() => {
  return (
    tableInfo.value.selections.length &&
    proxy.$permission('receiptOrder:remove') &&
    tableInfo.value.selections.filter((row) => row.status !== 1).length === 0
  )
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'receipt_order_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function _search() {
  console.log(filterInfo.value.query.queryMap)
  filterInfo.value.query.queryParams = {
    settleType: filterInfo.value.query.queryMap.settleType.value
  }
  search()
}
function _advancedSearchShow() {
  advancedSearchShow()
}
function _clearSearch() {
  clearSearch()
}

const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}

async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'receipt_order',
      columnName: 'supplier_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'supplierAuth',
    },
  ]
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}

function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: 'receiptOrderList-com.slip.spd.entity.vo.receipt.ReceiptOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getReceiptOrderCustomizeListPage
      getList()
    }
  })
}
function downloadFile() {
  let query = {
    sort: 'create_time desc',
    supplierAuth: 'supplierId',
  }
  downloadFileReceiptOrder(query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function handleClose() {
  dialogInfo.value.visible = false
}
function returnModify() {
  getList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//创建
function create() {
  modifyInfo.value.title = '新增发票单'
  modifyInfo.value.visible = true
  modifyInfo.value.orderId = null
}
//更新
function update(row) {
  modifyInfo.value.title = '修改发票单'
  modifyInfo.value.orderId = row.id
  modifyInfo.value.visible = true
}
//展示明细
function showDetail(row) {
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}

//提交
function submit(row) {
  const ids = [row.id]
  submitReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//驳回
function reject(row) {
  const ids = [row.id]
  rejectReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//审核
function ratify(row) {
  const ids = _getIds(row)
  ratifyReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//撤回
function revoke(row) {
  const ids = _getIds(row)
  revokeReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//作废
function cancel(row) {
  const ids = _getIds(row)
  cancelReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function del(row) {
  const ids = _getIds(row)
  deleteReceiptOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  excelReceiptOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

function printList() {
  fatchTemplateByCode({
    resourceCode: 'receiptOrder:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function pageInfo(obj) {
  page.value = obj
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
function getPrintData(temp, flag) {
  let params = {
    customizeDto: filterInfo.value.query,
    ...page.value,
    page: flag,
  }
  printReceiptOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
</script>

<style scoped></style>
